<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${article != null ? '编辑文章' : '创建文章'} + ' - 学生知识管理系统'">编辑文章 - 学生知识管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f5f5;
            line-height: 1.6;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .nav {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 2rem;
        }
        
        .logo {
            font-size: 1.5rem;
            font-weight: bold;
        }
        
        .nav-links {
            display: flex;
            list-style: none;
            gap: 2rem;
        }
        
        .nav-links a {
            color: white;
            text-decoration: none;
            transition: opacity 0.3s;
        }
        
        .nav-links a:hover {
            opacity: 0.8;
        }
        
        .container {
            max-width: 1000px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        
        .page-header {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .page-title {
            font-size: 1.8rem;
            color: #333;
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 5px;
            font-size: 1rem;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            transition: background 0.3s;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5a6fd8;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .form-container {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #333;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
            font-family: inherit;
        }
        
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }
        
        .form-group textarea {
            min-height: 400px;
            resize: vertical;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
        }
        
        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 2rem;
            padding-top: 2rem;
            border-top: 1px solid #eee;
        }
        
        .editor-toolbar {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1rem;
            padding: 0.5rem;
            background: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 5px 5px 0 0;
        }
        
        .editor-btn {
            padding: 0.5rem;
            border: none;
            background: transparent;
            border-radius: 3px;
            cursor: pointer;
            font-size: 0.875rem;
            transition: background 0.3s;
        }
        
        .editor-btn:hover {
            background: #e9ecef;
        }
        
        .editor-btn.active {
            background: #667eea;
            color: white;
        }
        
        .preview-container {
            display: none;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 1rem;
            background: white;
            min-height: 400px;
        }
        
        .preview-container.active {
            display: block;
        }
        
        .file-upload {
            border: 2px dashed #ddd;
            border-radius: 5px;
            padding: 2rem;
            text-align: center;
            cursor: pointer;
            transition: border-color 0.3s;
        }
        
        .file-upload:hover {
            border-color: #667eea;
        }
        
        .file-upload.dragover {
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.1);
        }
        
        .file-upload input {
            display: none;
        }
        
        .uploaded-files {
            margin-top: 1rem;
        }
        
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem;
            background: #f8f9fa;
            border-radius: 3px;
            margin-bottom: 0.5rem;
        }
        
        .file-item .file-name {
            font-weight: 500;
        }
        
        .file-item .file-size {
            color: #666;
            font-size: 0.875rem;
        }
        
        .file-item .file-actions {
            display: flex;
            gap: 0.5rem;
        }
        
        .file-item .file-actions button {
            padding: 0.25rem 0.5rem;
            border: none;
            border-radius: 3px;
            font-size: 0.75rem;
            cursor: pointer;
        }
        
        .alert {
            padding: 1rem;
            border-radius: 5px;
            margin-bottom: 1rem;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        @media (max-width: 768px) {
            .page-header {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
            
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .form-actions {
                flex-direction: column;
            }
            
            .editor-toolbar {
                flex-wrap: wrap;
            }
        }
    </style>
</head>
<body>
    <header class="header">
        <nav class="nav">
            <div class="logo">🎓 学生知识管理系统</div>
            <ul class="nav-links">
                <li><a href="/">首页</a></li>
                <li><a href="/articles">文章</a></li>
                <li><a href="/categories">分类</a></li>
                <li><a href="/profile">个人中心</a></li>
                <li><a href="/logout">退出</a></li>
            </ul>
        </nav>
    </header>
    
    <div class="container">
        <div class="page-header">
            <h1 class="page-title" th:text="${article != null ? '编辑文章' : '创建文章'}">编辑文章</h1>
            <a href="/articles" class="btn btn-secondary">← 返回文章列表</a>
        </div>
        
        <div th:if="${message}" class="alert alert-success" th:text="${message}">操作成功</div>
        <div th:if="${error}" class="alert alert-error" th:text="${error}">操作失败</div>
        
        <div class="form-container">
            <form th:action="${article != null ? '/articles/' + article.id + '/update' : '/articles/create'}" 
                  method="post" enctype="multipart/form-data">
                
                <div class="form-group">
                    <label for="title">文章标题 *</label>
                    <input type="text" id="title" name="title" 
                           th:value="${article != null ? article.title : ''}" 
                           placeholder="请输入文章标题" required>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="categoryId">分类 *</label>
                        <select id="categoryId" name="categoryId" required>
                            <option value="">请选择分类</option>
                            <option th:each="category : ${categories}" 
                                    th:value="${category.id}" 
                                    th:text="${category.name}"
                                    th:selected="${article != null and article.category != null and article.category.id == category.id}">分类名</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="status">状态</label>
                        <select id="status" name="status">
                            <option value="DRAFT" th:selected="${article == null or article.status.name() == 'DRAFT'}">草稿</option>
                            <option value="PUBLISHED" th:selected="${article != null and article.status.name() == 'PUBLISHED'}">发布</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="summary">文章摘要</label>
                    <textarea id="summary" name="summary" rows="3" 
                              th:text="${article != null ? article.summary : ''}" 
                              placeholder="请输入文章摘要（可选）"></textarea>
                </div>
                
                <div class="form-group">
                    <label for="content">文章内容 *</label>
                    <div class="editor-toolbar">
                        <button type="button" class="editor-btn" onclick="toggleMode('edit')" id="edit-btn">📝 编辑</button>
                        <button type="button" class="editor-btn" onclick="toggleMode('preview')" id="preview-btn">👁️ 预览</button>
                        <button type="button" class="editor-btn" onclick="insertText('**', '**')">B</button>
                        <button type="button" class="editor-btn" onclick="insertText('*', '*')">I</button>
                        <button type="button" class="editor-btn" onclick="insertText('# ', '')">H1</button>
                        <button type="button" class="editor-btn" onclick="insertText('## ', '')">H2</button>
                        <button type="button" class="editor-btn" onclick="insertText('- ', '')">列表</button>
                        <button type="button" class="editor-btn" onclick="insertText('```\n', '\n```')">代码</button>
                        <button type="button" class="editor-btn" onclick="insertText('[', '](url)')">链接</button>
                        <button type="button" class="editor-btn" onclick="insertText('![', '](url)')">图片</button>
                    </div>
                    <textarea id="content" name="content" 
                              th:text="${article != null ? article.content : ''}" 
                              placeholder="请输入文章内容，支持 Markdown 格式" required></textarea>
                    <div id="preview" class="preview-container"></div>
                </div>
                
                <div class="form-group">
                    <label>附件上传</label>
                    <div class="file-upload" onclick="document.getElementById('files').click()">
                        <input type="file" id="files" name="files" multiple accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.gif">
                        <p>📎 点击或拖拽文件到此处上传</p>
                        <p style="font-size: 0.875rem; color: #666;">支持 PDF、Word、图片等格式，单个文件不超过 10MB</p>
                    </div>
                    <div id="uploaded-files" class="uploaded-files"></div>
                </div>
                
                <div class="form-actions">
                    <button type="button" onclick="saveDraft()" class="btn btn-secondary">💾 保存草稿</button>
                    <button type="submit" class="btn btn-success">✅ 发布文章</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        let currentMode = 'edit';
        
        function toggleMode(mode) {
            currentMode = mode;
            const editBtn = document.getElementById('edit-btn');
            const previewBtn = document.getElementById('preview-btn');
            const content = document.getElementById('content');
            const preview = document.getElementById('preview');
            
            if (mode === 'edit') {
                editBtn.classList.add('active');
                previewBtn.classList.remove('active');
                content.style.display = 'block';
                preview.classList.remove('active');
            } else {
                editBtn.classList.remove('active');
                previewBtn.classList.add('active');
                content.style.display = 'none';
                preview.classList.add('active');
                updatePreview();
            }
        }
        
        function insertText(before, after) {
            const textarea = document.getElementById('content');
            const start = textarea.selectionStart;
            const end = textarea.selectionEnd;
            const selectedText = textarea.value.substring(start, end);
            const newText = before + selectedText + after;
            
            textarea.value = textarea.value.substring(0, start) + newText + textarea.value.substring(end);
            textarea.focus();
            textarea.setSelectionRange(start + before.length, start + before.length + selectedText.length);
        }
        
        function updatePreview() {
            const content = document.getElementById('content').value;
            const preview = document.getElementById('preview');
            
            // 简单的 Markdown 预览（实际项目中建议使用专业的 Markdown 解析库）
            let html = content
                .replace(/^# (.*$)/gim, '<h1>$1</h1>')
                .replace(/^## (.*$)/gim, '<h2>$1</h2>')
                .replace(/^### (.*$)/gim, '<h3>$1</h3>')
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                .replace(/\*(.*?)\*/g, '<em>$1</em>')
                .replace(/^- (.*$)/gim, '<li>$1</li>')
                .replace(/\n/g, '<br>');
            
            preview.innerHTML = html || '<p style="color: #666;">预览内容将在这里显示...</p>';
        }
        
        function saveDraft() {
            const form = document.querySelector('form');
            const statusSelect = document.getElementById('status');
            statusSelect.value = 'DRAFT';
            form.submit();
        }
        
        // 文件上传处理
        const fileUpload = document.querySelector('.file-upload');
        const fileInput = document.getElementById('files');
        const uploadedFiles = document.getElementById('uploaded-files');
        
        fileUpload.addEventListener('dragover', (e) => {
            e.preventDefault();
            fileUpload.classList.add('dragover');
        });
        
        fileUpload.addEventListener('dragleave', () => {
            fileUpload.classList.remove('dragover');
        });
        
        fileUpload.addEventListener('drop', (e) => {
            e.preventDefault();
            fileUpload.classList.remove('dragover');
            const files = e.dataTransfer.files;
            handleFiles(files);
        });
        
        fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
        });
        
        function handleFiles(files) {
            Array.from(files).forEach(file => {
                if (file.size > 10 * 1024 * 1024) {
                    alert(`文件 ${file.name} 超过 10MB 限制`);
                    return;
                }
                
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                    <div>
                        <span class="file-name">${file.name}</span>
                        <span class="file-size">(${formatFileSize(file.size)})</span>
                    </div>
                    <div class="file-actions">
                        <button type="button" onclick="removeFile(this)" style="background: #dc3545; color: white;">删除</button>
                    </div>
                `;
                uploadedFiles.appendChild(fileItem);
            });
        }
        
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        function removeFile(button) {
            button.closest('.file-item').remove();
        }
        
        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            toggleMode('edit');
        });
    </script>
</body>
</html>